package hczc.longcai.com.hccrowdfunding.activity;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;

import hczc.longcai.com.hccrowdfunding.R;
import hczc.longcai.com.hccrowdfunding.activity.beans.Code;
import hczc.longcai.com.hccrowdfunding.activity.beans.FindPass;
import hczc.longcai.com.hccrowdfunding.utils.httputils.HttpPath;
import hczc.longcai.com.hccrowdfunding.utils.httputils.LoadDatas;
import hczc.longcai.com.hccrowdfunding.utils.json.ParseJSON;

import static android.text.TextUtils.isEmpty;

public class FindPasswdActivity extends BaseActivity implements View.OnClickListener {

    private static final int SEND_SUCCESS = 0;
    private static final String TAG = "FindPasswdActivity";

    private EditText number;
    private EditText code;
    private EditText passwd;
    private EditText affirm;

    private String codeId;

    private FindPassAsyncTask asyncTask;


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            switch (what) {
                case SEND_SUCCESS:
                    Code code = (Code) msg.obj;
                    String status = code.getStatus();
                    if ("1".equals(status)) {
                        codeId = code.getId();
                        Toast.makeText(FindPasswdActivity.this, code.getTips(), Toast.LENGTH_SHORT).show();
                        Log.d(TAG, code.toString());
                    } else {
                        Toast.makeText(FindPasswdActivity.this, code.getTips(), Toast.LENGTH_SHORT).show();
                    }

                    break;
            }
        }
    };
    private LoadDatas loadDatas;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_passwd);

        loadDatas = new LoadDatas();

        initViews();
    }

    private void initViews() {
        findViewById(R.id.head_back).setOnClickListener(this);
        ((TextView) findViewById(R.id.head_title)).setText("找回密码");
        findViewById(R.id.headbar_background).setBackgroundColor(Color.parseColor("#00000000"));


        initInputs();
    }

    /**
     * 初始化输入框和确定按钮
     */

    private void initInputs() {
        number = ((EditText) findViewById(R.id.find_input_number_edit));
        code = ((EditText) findViewById(R.id.find_input_code_edit));
        passwd = ((EditText) findViewById(R.id.find_input_passwd_edit));
        affirm = ((EditText) findViewById(R.id.find_input_affirm_edit));

        findViewById(R.id.find_hqyzm).setOnClickListener(this);

        findViewById(R.id.find_button).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.head_back:
                finish();
                break;

            case R.id.find_button:
                findSuccess();
                break;

            case R.id.find_hqyzm:
                getCode();
                break;
        }
    }

    private void getCode() {
        final String number = this.number.getText().toString().trim();
        if (TextUtils.isEmpty(number)) {
            Toast.makeText(FindPasswdActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
            setFocus(this.number);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String findpass = HttpPath.getURL_Code(number, "findpass");
                    byte[] datas = loadDatas.getDatas(findpass);
                    String JSON = new String(datas, 0, datas.length);
                    Code code = ParseJSON.parseCode(JSON);
                    Message message = handler.obtainMessage();
                    message.what = 0;
                    message.obj = code;
                    handler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 判断是否操作成功
     */

    private void findSuccess() {

        String c_number = number.getText().toString().trim();
        String c_code = code.getText().toString().trim();
        String c_passwd = passwd.getText().toString().trim();
        String c_affirm = affirm.getText().toString().trim();

        if (isEmpty(c_number, c_code, c_passwd, c_affirm)) {
            asyncTask = new FindPassAsyncTask(c_number, c_code, codeId, c_passwd);
            asyncTask.execute(((Void) null));
        }

    }

    /**
     * 判断输入的内容是否满足条件
     *
     * @param c_number 输入的电话号码
     * @param c_code   输入的验证码
     * @param c_passwd 输入的密码
     * @param c_affirm 确认密码
     * @return 若符合条件返回true
     */
    private boolean isEmpty(String c_number, String c_code, String c_passwd, String c_affirm) {
        boolean flag = true;

        if (TextUtils.isEmpty(c_number)) {
            Toast.makeText(FindPasswdActivity.this, "请输入手机号码", Toast.LENGTH_SHORT).show();
            setFocus(number);
            flag = false;
            return flag;
        } else if (c_number.length() != 11) {
            Toast.makeText(FindPasswdActivity.this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            number.setText("");
            setFocus(number);
            flag = false;
            return flag;
        }

        if (TextUtils.isEmpty(c_code)) {
            Toast.makeText(FindPasswdActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
            setFocus(code);
            flag = false;
            return flag;
        }

        if (TextUtils.isEmpty(c_passwd)) {
            Toast.makeText(FindPasswdActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
            setFocus(passwd);
            flag = false;
            return flag;
        } else if (c_passwd.length() <= 6) {
            Toast.makeText(FindPasswdActivity.this, "密码过短，请重新输入", Toast.LENGTH_SHORT).show();
            passwd.setText("");
            setFocus(passwd);
            flag = false;
            return flag;
        } else if (c_passwd.length() > 20) {
            Toast.makeText(FindPasswdActivity.this, "密码过长，请重新输入", Toast.LENGTH_SHORT).show();
            passwd.setText("");
            setFocus(passwd);
            flag = false;
            return flag;
        }

        if (TextUtils.isEmpty(c_affirm)) {
            Toast.makeText(FindPasswdActivity.this, "请再次输入密码", Toast.LENGTH_SHORT).show();
            setFocus(affirm);
            flag = false;
            return flag;
        } else if (!c_affirm.equals(c_passwd)) {
            Toast.makeText(FindPasswdActivity.this, "两次输入的密码不一致，请重新输入", Toast.LENGTH_SHORT).show();
            affirm.setText("");
            setFocus(affirm);
            flag = false;
            return flag;
        }


        return flag;
    }

    /**
     * 设置EditText的焦点
     *
     * @param et 要设置的EditText
     */
    private void setFocus(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();
        et.findFocus();
    }

    class FindPassAsyncTask extends AsyncTask<Void, Void, Boolean> {

        private String info;

        private String txtPhone;
        private String txtCode;
        private String codeId;
        private String txtPassword;

        public FindPassAsyncTask(String txtPhone, String txtCode, String codeId, String txtPassword) {
            this.txtPhone = txtPhone;
            this.txtCode = txtCode;
            this.codeId = codeId;
            this.txtPassword = txtPassword;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean flag = false;
            try {
                String url_findpass = HttpPath.getURL_Findpass(txtPhone, txtCode, codeId, txtPassword);
                Log.d(TAG, url_findpass);
                byte[] datas = loadDatas.getDatas(url_findpass);
                String JSON = new String(datas, 0, datas.length);
                FindPass findPass = ParseJSON.parseFind(JSON);
                String status = findPass.getStatus();
                if ("1".equals(status)) {
                    flag = true;
                } else {
                    info = findPass.getTips();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


            return flag;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
                Toast.makeText(FindPasswdActivity.this, "重置密码成功！请登陆", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(FindPasswdActivity.this, info, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
